let http = require('http')
let Formidable = require('formidable')
let server = http.createServer((request, response) => {
  response.setHeader('Access-Control-Allow-Origin', '*')
  let url = request.url
  let method = request.method.toLowerCase()
  if (url === '/api/upload' && method === 'post') {
    //执行文件上传
    let formidable = new Formidable({
      multiples: true,
      uploadDir: __dirname + '/upload',
      keepExtensions: true
    })
    console.log(formidable)
    let fields = []
    let files = []
    //解析请求的文本域
    formidable.on('field', (fieldName, value) => {
      let item = { fieldName, value }
      console.log(item)
      fields.push(item)
    }).on('file', (fileName, file) => {
      //解析的是文件
      files.push({ fileName, file })
    }).on('end', () => {
      //解析结束
      console.log(fields)
      console.log(files)
    })
    //执行request的解析
    formidable.parse(request)
    response.end('111')
  }
})

server.listen(8080, '127.0.0.1', () => {
  console.log('server on 8080')
})
